package cn.texous.web.parsing.book.config.runner;

import cn.texous.web.parsing.book.manager.RedisManager;
import cn.texous.web.parsing.book.model.entity.mysql.AnaBook;
import cn.texous.web.parsing.book.service.api.mysql.AnaBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

/**
 * Redis 缓存初始化
 * TODO 需要优化，增量缓存
 *
 * @author Showa.L
 * @since 2020/3/12 9:50
 */
@Slf4j
@Component
public class RedisInfoInitRunner implements ApplicationRunner {

    @Autowired
    private AnaBookService anaBookService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("【初始化 REDIS 必要信息】......");
        // 缓存所有书籍
        cacheBook(1, 10000);
    }

    private void cacheBook(Integer page, Integer size) {
        List<AnaBook> books = anaBookService.findLimit(page, size);
        Optional.ofNullable(books)
                .ifPresent(bs -> bs.stream().forEach(RedisManager::cacheBookInfo));
        if (books.size() == size)
            cacheBook(++page, size);
    }

}
